<template>
  <!-- 饼图 -->
  <v-chart class="chart" :option="option" />
  <!-- 折线图 -->
  <v-chart class="chart2" :option="option2" />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
// 饼图静态数据
const data = ref([
  // { value: 1048, name: 'Search Engine' },
])
// 让option响应data的更新--需要计算属性
const option = computed(() => {
  // 模板
  return {
    title: {
      text: '文章类别分布图',
      subtext: '显示各个分类的文章数',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: data.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
})
// 柱状图
// 横坐标
const data2 = ref([])
//浏览量
const data3 = ref([])
// 评论量
const data4 = ref([])
const option2 = computed(() => {
  return {
    title: {
      text: '文章数据详情图',
      subtext: '显示各个文章下的浏览量和评论数',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['浏览量', '评论数'],
    },
    toolbox: {
      show: true,
      feature: {
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },
    calculable: true,
    xAxis: [
      {
        type: 'category',
        // prettier-ignore
        //横轴
        data: data2.value,
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    // 数轴
    series: [
      {
        name: '浏览量',
        type: 'bar',
        data: data3.value,
        // markLine: {
        //   data: [{ type: 'average', name: 'Avg' }],
        // },
      },
      {
        name: '评论数',
        type: 'bar',
        data: data4.value,
        // markLine: {
        //   data: [{ type: 'average', name: 'Avg' }],
        // },
      },
    ],
  }
})
// 从接口中获取数据
onMounted(() => {
  // 饼
  axios.get('/pieChart').then((res) => {
    console.log(res.data.result)
    data.value = res.data.result
  })
  // 柱
  axios.get('/barChart').then((res) => {
    const arr = res.data.result
    console.log(arr)
    /* 
    0: Object { 
      article_title: "新时代总书记寄望青年", //data2
      article_views: 13, //data3
      count: 20 //data4
    } 
    */
    /* 遍历接口取到的对象,并按名称重新分组原来的数组 */
    for (var i = 0; i < arr.length; i++) {
      if (typeof arr[i] == 'object') {
        data2.value.push(arr[i].article_title)
        data3.value.push(arr[i].article_views)
        data4.value.push(arr[i].count)
      }
    }
  })
})
</script>

<style scoped>
.chart {
  height: 80vh;
}
</style>
